package ext.tianma.util;


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import wt.enterprise.RevisionControlled;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.WTObject;
import wt.inf.container.WTContained;
import wt.lifecycle.LifeCycleHelper;
import wt.lifecycle.LifeCycleTemplate;
import wt.lifecycle.LifeCycleTemplateReference;
import wt.lifecycle.State;
import wt.method.RemoteAccess;
import wt.method.RemoteMethodServer;
import wt.part.WTPart;
import wt.part.WTPartMaster;
import wt.pds.StatementSpec;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.type.TypeDefinitionForeignKey;
import wt.type.TypeDefinitionReference;
import wt.type.Typed;
import wt.type.TypedUtilityServiceHelper;
import wt.util.WTException;
import wt.util.WTProperties;
import wt.vc.Iterated;
import wt.vc.VersionControlHelper;
import wt.vc.config.ConfigHelper;
import wt.vc.config.ConfigSpec;
import wt.vc.config.LatestConfigSpec;
import wt.vc.views.View;
import wt.vc.wip.WorkInProgressHelper;

public class BatchModificationForFinPart implements RemoteAccess {
	private static final String CLASSNAME = BatchModificationForFinPart.class.getName();
	private static String wtHome = "";
	static {
		WTProperties wtproperties;
		try {
			wtproperties = WTProperties.getLocalProperties();
			wtHome = wtproperties.getProperty("wt.home", "");
			//userNoMap = parseUserNoCSVFile();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 根据类型获取部件
	 * 
	 * @param partType
	 * @return
	 * @throws WTException
	 * @throws IOException 
	 */
	public static String getPartByType() throws WTException, IOException {
		System.out.println("statr update========");
		long start = System.currentTimeMillis();
		List<WTObject> partList = new ArrayList<WTObject>();
		String filepath = wtHome+ File.separator + "temp"+ File.separator + "modifyLdapFinPart.log";
		File myFilePath = new File(filepath);
	      if(!myFilePath.exists()){
	        myFilePath.createNewFile();
	      }
		FileWriter fileWriter = new FileWriter(myFilePath);
		String filepathFail = wtHome+ File.separator + "temp"+ File.separator + "modifyLdapFailFinPart.log";
		File myFilePathFail = new File(filepathFail);
	      if(!myFilePathFail.exists()){
	    	  myFilePathFail.createNewFile();
	      }
		FileWriter fileWriterFail = new FileWriter(myFilePathFail);
		// 通过类型的内部名称，获取类型定义的对象
		TypeDefinitionReference ref;            
		ref =TypedUtilityServiceHelper.service.getTypeDefinitionReference("cn.tianma.FinishedGood");//成品

		//ref = TypedUtilityServiceHelper.service.getTypeDefinitionReference("cn.tianma.SemiFinishedGood");// 半成品
		System.out.println(ref);
		if (ref != null) {
			long IdLong = ref.getKey().getBranchId();
			System.out.println("======>>>IdLong====="+IdLong);
			QuerySpec qs = new QuerySpec(WTPart.class);
			// 通过类型的内部名称查询
			qs.appendWhere(
					new SearchCondition(WTPart.class,
							Typed.TYPE_DEFINITION_REFERENCE + "." + TypeDefinitionReference.KEY + "."
									+ TypeDefinitionForeignKey.BRANCH_ID,
							SearchCondition.EQUAL, IdLong),
					new int[] { 0 });
			qs.appendAnd();
			qs.appendOpenParen();
			qs.appendWhere(
					new SearchCondition(WTPart.class, WTPart.LIFE_CYCLE_STATE, SearchCondition.EQUAL, "NewProduct"));//新品
			qs.appendOr();
			qs.appendWhere(
					new SearchCondition(WTPart.class, WTPart.LIFE_CYCLE_STATE, SearchCondition.EQUAL, "INWORK"));//正在工作
			qs.appendOr();
			qs.appendWhere(
					new SearchCondition(WTPart.class, WTPart.LIFE_CYCLE_STATE, SearchCondition.EQUAL, "SubmitReview"));//提交审阅
			qs.appendOr();
			qs.appendWhere(
					new SearchCondition(WTPart.class, WTPart.LIFE_CYCLE_STATE, SearchCondition.EQUAL, "UNDERREVIEW"));//正在审阅
			qs.appendOr();
			qs.appendWhere(
					new SearchCondition(WTPart.class, WTPart.LIFE_CYCLE_STATE, SearchCondition.EQUAL, "NewProductModify"));//新品修改
			qs.appendOr();
			qs.appendWhere(
					new SearchCondition(WTPart.class, WTPart.LIFE_CYCLE_STATE, SearchCondition.EQUAL, "REWORK"));//重新工作
			qs.appendCloseParen();
			qs.appendAnd();
			SearchCondition latest = VersionControlHelper.getSearchCondition(WTPart.class, true); 
			qs.appendSearchCondition(latest);
			System.out.println("qs====>>>>" + qs.toString());
			QueryResult qr = PersistenceHelper.manager.find((StatementSpec) qs);
			//qr = new LatestConfigSpec().process(qr);
			System.out.println("===>>>" + qr.size());
			while (qr.hasMoreElements()) {
				WTPart part = (WTPart) qr.nextElement();
				partList.add(part);
			}

			int total = partList.size();

			System.out.println("共查询到 " + total + " 条数据...");
			fileWriter.write("共查询到 " + total + " 条数据...\n");
			int index = 0;
			for (int i = 0; i < partList.size(); i++) {

				WTPart obj = (WTPart) partList.get(i);

				fileWriter.write("[正在处理]第 " + (i + 1) + "/" + total + " 条数据：" + obj.getDisplayIdentifier() + " ..\n");

				if (isCheckOut(obj)) {

					fileWriterFail.write(
							"[检出状态]跳过第 " + (i + 1) + "/" + total + " 条数据：" + obj.getDisplayIdentifier() + "..\n");
					continue;
				}

				RevisionControlled controlled = (RevisionControlled) obj;

				LifeCycleTemplate lifeCycleTemplate = (LifeCycleTemplate) controlled.getLifeCycleTemplate().getObject();
				if (lifeCycleTemplate.isLatestIteration()) {

					fileWriterFail.write(
							"[已经为最新]跳过第 " + (i + 1) + "/" + total + " 条数据：" + obj.getDisplayIdentifier() + " ..\n");
					continue;
				}

				State state = controlled.getLifeCycleState();
				System.out.println("state==================>>>"+state);
				String lifeCycleName = controlled.getLifeCycleName();
				LifeCycleTemplateReference lifeCycleTemplateReference = LifeCycleHelper.service
						.getLifeCycleTemplateReference(lifeCycleName,
								((WTContained) controlled).getContainerReference());

				try {
					LifeCycleHelper.service.reassign(controlled, lifeCycleTemplateReference);
					LifeCycleHelper.service.setLifeCycleState(controlled, state);
				} catch (WTException e) {
					System.out.println(e.getLocalizedMessage());
				}

				fileWriter.write("[处理完成]第 " + (i + 1) + "/" + total + " 条数据：" + controlled.getDisplayIdentifier()
						+ "(" + lifeCycleName + "," + state.getDisplay(Locale.SIMPLIFIED_CHINESE) + ")\n");
				index = index+1;
				if(index==5000) {
					System.out.println("处理完5000...");
					fileWriter.write("处理完5000...");
					long end = System.currentTimeMillis();
					fileWriter.write("****** 执行修改生命周期接口5000用时间:"+(end-start)/1000+"秒\n");
					fileWriter.close();
					fileWriterFail.close();
					return "ok";
				}
			}
			System.out.println("全部处理完成...");
			fileWriter.write("全部处理完成...");
			long end = System.currentTimeMillis();
			fileWriter.write("****** 执行修改生命周期接口共用时间:"+(end-start)/1000+"秒\n");
		}
		fileWriter.close();
		fileWriterFail.close();
		return "success";
	}

	public static void main(String[] args) throws WTException, IOException {
		String type = args[0];
		String states = args[1];
		if (!RemoteMethodServer.ServerFlag) {
			String method = "getPartByType";
		
			try {
				System.out.println("Debug   RemoteMethodServer...");
				RemoteMethodServer server = RemoteMethodServer.getDefault();
				server.setUserName("wcadmin");
				server.setPassword("tmadmin");
				System.out.println("...");
				RemoteMethodServer.getDefault().invoke(method, CLASSNAME, null, null, null);
				System.out.println("Debug  end RemoteMethodServer...");
			} catch (RemoteException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}

		} else {
			System.out.println("Debug   importBoms...");
			System.out.println("1111======>>>");
			getPartByType();
			System.out.println("Debug   end importBoms...");
		}

	}

	/**
	 * 判断该零件是否已经出库
	 * 
	 * @param part
	 *            零件对象
	 * @return true:出库<br>
	 *         false:未出库
	 */
	public static boolean isCheckOut(WTPart part) {
		boolean isCheckOut = false;
		if (part != null) {
			try {
				isCheckOut = WorkInProgressHelper.isCheckedOut(part);/* 获取零件的出库状态 */
			} catch (WTException e) {
				e.printStackTrace();
			}
		} // end if

		return isCheckOut;
	}

	/***
	 * 根据WTPartMaster获取最新零部件
	 * 
	 * @param paramWTPartMaster
	 * @return
	 * @throws WTException
	 */
	public static WTPart getLatestPartByPartMaster(WTPartMaster paramWTPartMaster) throws WTException {
		Iterated localIterated = null;
		boolean bool = false;
		LatestConfigSpec localLatestConfigSpec = new LatestConfigSpec();

		QueryResult localQueryResult = ConfigHelper.service.filteredIterationsOf(paramWTPartMaster,
				localLatestConfigSpec);
		if ((localQueryResult != null) && (localQueryResult.size() <= 0)) {
			ConfigSpec localConfigSpec = ConfigHelper.service.getDefaultConfigSpecFor(WTPartMaster.class);
			localQueryResult = ConfigHelper.service.filteredIterationsOf(paramWTPartMaster, localConfigSpec);
		}

		while ((localQueryResult.hasMoreElements()) && (!bool)) {
			localIterated = (Iterated) localQueryResult.nextElement();
			bool = localIterated.isLatestIteration();
		}
		return (WTPart) localIterated;
	}

}

